﻿/**
 * 工具js
 */

window.showWait = window.showWait || {hide:function(){}};

/**
 * 弹出框
 * @author rubekid
 * Created by Administrator on 2015/10/22.
 */
(function(){
    var coverEle = '<div class="dialog-cover" style="display:none;"></div>';
    var dialogEle = '<div class="dialog-wrapper"  style="display:none;"><!--<div class="dialog-header">提 示</div>--> <div class="dialog-content"></div><div class="btn-box"></div></div>';
    var selectorEle = '<div class="dialog-wrapper simple-dialog"  style="display:none;"><div class="dialog-header">提 示 </div> <div class="dialog-content pd-sm"></div></div>';
    var loadingTarget = $('<div class="toast toast-box" style="display:none;"><div class="toast-content loading-wrap"><div class="text-center"><i class="fa-spin fa-refresh"></i></div><div class="loading-content"></div></div>');
    var toastTarget = $('<div class="toast toast-box" style="display:none;"><div class="toast-content"></div></div>');
    var replyTarget = $('<div class="reply-dialog"><div class="js_editor needsclick" contentEditable="true"></div><div class="btn-box"><a href="javascript:;" class="btn btn-cube float-r btn-primary">发表评论</a></div></div>');
    var coverTarget = $(coverEle);

    $(function(){
        $(document.body).append(loadingTarget);
        $(document.body).append(toastTarget);
    });

    function Dialog(config){
        config = config || {};
        var ele  = config.isSelector ? selectorEle : dialogEle;

        this.cover = coverTarget;
        this.dialog = $(ele);
        this.dialog.find(".dialog-content").html(config.content);
        var _this = this;

        if(config.title){
            this.dialog.find(".dialog-header").html(config.title);
        }
        if(!config.isSelector){
            var buttons = config.buttons || [{text:"确定",event:function(){}}];
            this.btnBox = this.dialog.find(".btn-box");
            for(var i= 0,len=buttons.length; i<len; i++){
                (function(index){
                    var button = buttons[index];
                    var className = "btn";
                    if(button.className){
                        className += " " + button.className;
                    }
                    var buttonTarget = $('<a href="javascript:;" class="'+ className +'">'+button.text+'</a>');
                    if(button.class){
                        buttonTarget.addClass(button.class);
                    }
                    buttonTarget.bind("click", function(){
                        button.event(_this);
                    });
                    _this.btnBox.append(buttonTarget);
                })(i);
            }
        }

        $(document.body).append(this.cover);
        $(document.body).append(this.dialog);
    }

    Dialog.prototype = {
        open:function(){
            this.cover.show();
            this.dialog.show();
            this.dialog.css({
                marginTop: -this.dialog.height() / 2
            });
        },
        close:function(){
            this.cover.hide();
            this.dialog.hide();
        },
        destory:function(){
            this.dialog.remove();
            this.cover.remove();
        },
        cancel:function(){
            this.cover.hide();
            this.dialog.hide();
        },
        find:function(selector){
            return $(selector,this.dialog);
        }
    }

    window.Modal = {
        loading:function(message){
            message = message || "加载中……";
            loadingTarget.find(".loading-content").text(message);
            loadingTarget.show();
        },
        dismissLoading:function(){
            loadingTarget.find(".loading-content").text("");
            loadingTarget.hide();
        },
        error:function(message){
            this.toast(message);
        },
        success:function(message){
            this.toast(message);
        },
        toast:function(message, timeout){
            if(this.timeout){
                clearTimeout(this.timeout);
            }
            toastTarget.stop();
            toastTarget.find(".toast-content").text(message);
            toastTarget.show();
            this.timeout = setTimeout(function(){
                toastTarget.fadeOut("normal", function(){
                    toastTarget.hide();
                    toastTarget.find(".toast-content").text("");
                    toastTarget.css({opactiy:1});
                });
            }, timeout || 1500);
        },
        alert : function(content){
            var dialog = new Dialog({
                content:content,
                buttons:[
                    {
                        text:"确定",
                        event:function(target){
                            target.close();
                        }
                    }
                ]
            });
            dialog.open();
        },
        confirm:function(content, confirm, cancel){
            confirm = confirm || function(){return true;};
            cancel = cancel || function(){};
            var dialog = new Dialog({
                content:content,
                buttons:[

                    {
                        text:"确定",
                        className:"btn-primary-empty",
                        event:function(target){
                            var close = function(){
                                target.close();
                            };
                            if(confirm(close)){
                                close();
                            }
                        }
                    },
                    {
                        text:"取消",
                        event:function(target){
                            cancel();
                            target.close();
                        }
                    }
                ]
            });
            dialog.open();
        },
        showDialog : function(content, buttons){
            var dialog = new Dialog({
                content:content,
                buttons:buttons
            });
            dialog.open();
            return dialog;
        },
        showSimpleDialog:function(title, html){
            var dialog = new Dialog({
                title:'<b>' +title + '</b><a href="javascript:;" class="close">×</a>',
                content:html,
                isSelector:true
            });
            dialog.find(".close").on("click", function(){
                dialog.destory();
            });
            dialog.open();
            dialog.cover.on("click", function(){
                dialog.destory();
            });
            return dialog;
        }
    }

})(window.jQuery|| window.Zepto);

Date.prototype.Format = function(fmt){ //author: meizz   
	var o = {   
		"M+" : this.getMonth()+1,                 //月份   
		"d+" : this.getDate(),                    //日   
		"h+" : this.getHours(),                   //小时   
		"m+" : this.getMinutes(),                 //分   
		"s+" : this.getSeconds(),                 //秒   
		"q+" : Math.floor((this.getMonth()+3)/3), //季度   
		"S"  : this.getMilliseconds()             //毫秒   
	};
	if(/(y+)/.test(fmt)){
		fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
	}
	for(var k in o){
		if(new RegExp("("+ k +")").test(fmt)){
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
		}
	}
	return fmt;   
}  

/**
 * html特殊字符转义
 * 
 * @param str
 * @returns
 */
function htmlEncode(str) {
	if(str == ""||str == null||str == undefined)return "";
	var div = document.createElement("div");
	div.appendChild(document.createTextNode(str));
	return div.innerHTML.replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}

/**
 * 
 * @param str
 * @returns
 */
function htmlDecode(str, isText) {
	if(str == ""||str == null||str == undefined)return "";
	var div = document.createElement("div");
	if(isText){ //兼容纯文本换行
		div = document.createElement("pre");
	}
	div.innerHTML = str;
	return div.innerText || div.textContent;
}

/**
 * 转换特殊字符 
 */
function htmlEntities(text){
	if(!text){
		return "";
	}
	text = text.replace(/&/g, "&amp;");
	text = text.replace(/\"/g,"&quot;");
	text = text.replace(/</g, "&lt;");
	text = text.replace(/>/g, "&gt;");
	return text;
}

/**
 * 删除html标签
 * 
 * @param str
 * @returns
 */
/**
 * 检测是否含有windows非法文件名称
 */
function checkSpecial(str){
	var re=/[*?:|\\\/<>"]/;
    return re.test(str);
}
function delHtmlTag(str) {
	return str.replace(/<[^>]+>/g, "");// 去掉所有的html标记
}

function checkUrl(url) {
	var re = /^((requireOpenId:)?((http|https|ftp):\/\/)?([\w\u4e00-\u9fa5\-]+\.)+[\w\u4e00-\u9fa5\-]+(:\d+)?(\/[\w\u4e00-\u9fa5\-\.\/?\@\%\!\&=\+\~\:\#\;\,]*)?)$/ig;
	return re.test(url);
}

function checkPhone(num){
	return checkMobile(num) || checkTelephone(num);
}

function checkMobile(num){
	var re = /^1[3,4,5,7,8]\d{9}$/;
	return re.test(num);
}

function checkTelephone(num){
	var phoneReg = /(^\+86\.\d{3,5}\d{6,8}$)|(^\d{3}((\d-)|(-\d)|\d|-)\d{3}(\d|-|)\d{3}(\d|)$)/;
	return phoneReg.test(num);
}

function checkPHS(num){
	var re = /^0[0-9]{9,11}$/;
	return re.test(num);
}

function checkEmail(email){
	var re = /^[&~#$*%\u4e00-\u9fa5_0-9a-z\-\.\/\\]+@([\u4e00-\u9fa5-a-z0-9]+\.){1,5}[\u4e00-\u9fa5a-z]+$/i;
	return re.test(email);
}

function checkDomain(domain){
	var re = /^([\u4e00-\u9fa5-a-z0-9]+\.){1,5}[\u4e00-\u9fa5a-z]+$/i;
	return re.test(domain);
}

function checkNumber(number){
	var re = /^\d+$/;
	return number == 0 || re.test(number);
}

function checkDate(dateStr){
	var re = /^\d{4}(-)\d{2}(-)\d{2}$/;
	return re.test(dateStr);
}

function checkDateTime(dateTimestr){
	var re = /^\d{4}(-)\d{2}(-)\d{2}( )\d{2}:\d{2}:\d{2}$/;
	return re.test(dateTimestr);
}

function checkMoney(money){
	var re = /^(0|[1-9]\d*)(\.\d{1,2})?$/;
	return re.test(money);
}
//校验只包含数字和字母
function checkOnlyNumAndLetter(strVal){
	var re = /^[0-9a-zA-Z]*$/g;
	return re.test(strVal);
}

//校验订单号
function checkLogisticsCode(logisticsCode){
	var re = /^[0-9a-zA-Z]{2}\d{6,20}[0-9a-zA-Z]{2}$/;
	return re.test(logisticsCode);
}

function checkChineseAndEnAndUnderLine(String){
	var re=/^[\u4e00-\u9fa5_a-zA-Z]+$/;
	return re.test(String);
}

/**
 * 校验是否字符串包含中文字符
 * 
 * @returns
 */
function containChinese(string) {
	var re = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi;
	return re.test(string);
}

/**
 * 检验密码强度
 * @param password
 * @returns {Boolean}
 */
function checkStrength(password){
	var strength = 0;
	if (password.match(/[a-z]+/i)) {
		strength ++;
	}
	if (password.match(/[0-9]+/)) {
		strength ++;
	}
	if (password.match(/[\/,.~!@#$%^&*()\[\]_+\-=\:\";'\{\}\|\\><\?]+/)) {
		strength ++;
	}
	if(strength>1){
		return true;
	}else{
		return false;
	}
}

// 写cookies

function setCookie(name, value) {
	var Days = 30;
	var exp = new Date();
	exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
	document.cookie = name + "=" + escape(value) + ";expires="
			+ exp.toGMTString();
}

// 读取cookies
function getCookie(name) {
	var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
	if (arr = document.cookie.match(reg))
		return unescape(arr[2]);
	else
		return null;
}

// 删除cookies
function delCookie(name) {
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = getCookie(name);
	if (cval != null)
		document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

/**
 * 去除array中的重复元素
 * @param array
 * @returns {Array}
 */
function uniqueArray(array){
	var n = {},r=[]; //n为hash表，r为临时数组
	for(var i = 0; i < array.length; i++) //遍历当前数组
	{
		if (!n[array[i]]) //如果hash表中没有当前项
		{
			n[array[i]] = true; //存入hash表
			r.push(array[i]); //把当前数组的当前项push到临时数组里面
		}
	}
	return r;
}

/**
 * 判断array是否有重复元素
 * @param array
 * @returns boolean
 */
function isRepeat(arr){  
	  var hash = {};
	  for(var i in arr) { 
	     if(hash[arr[i]]){
	    	 return true;
	     }
	     hash[arr[i]] = true;
	     }
	     return false;	 
}

/**
 * 判断对象是否相等
 */
var isObjectEquals = function(obj1,obj2){
	if(obj1 == null && obj2 == null){
		return true;
	}
    if(typeof obj1 != typeof obj2){
        return false;
    }
    return $.param(obj1) == $.param(obj2);
};
/**
 * 深度拷贝对象
 * @param myObj
 * @returns
 */
function isClass(o){
    if(o===null) return "Null";
    if(o===undefined) return "Undefined";
    return Object.prototype.toString.call(o).slice(8,-1);
}
function deepClone(obj){
    var result,oClass=isClass(obj);
    
    if(oClass==="Object"){
        result={};
    }else if(oClass==="Array"){
        result=[];
    }else{
        return obj;
    }
    for(key in obj){
        var copy=obj[key];
        if(isClass(copy)=="Object"){
            result[key]=arguments.callee(copy);//递归调用
        }else if(isClass(copy)=="Array"){
            result[key]=arguments.callee(copy);
        }else{
            result[key]=obj[key];
        }
    }
    return result;
}

/**
 * 设置输入框提示信息
 * @param options
 * @author rubekid
 */
var supportPlaceHolder = (function(){
	var input = document.createElement("input");
	return "placeholder" in input;
})();


function setPlaceHolder(target, options){
	if(!target || target.get(0)._initTip){
		return false;
	}
	
	options = options ||{};
	var tipText = options.tipText || target.attr("placeholder") ||"";

	if(supportPlaceHolder){
		target.attr("placeholder", tipText);
		target.data("placeholder", tipText);
		target.bind({
			focus: function(){
				$(this).removeAttr("placeholder");
			},
			blur:function(){
				$(this).attr("placeholder", target.data("placeholder"));
			}
		});
		return ;
	}
	
	var color = options.color||"#999999";
	var inputPrompt = target.clone();
	var name =  target.attr("name");
	
	target.removeAttr("placeholder");
	target.attr("data-tip", tipText);
	target.show();
	if(inputPrompt.is(":input") && inputPrompt.attr("type") != "text" && inputPrompt.get(0).tagName != "TEXTAREA"){
		inputPrompt = $('<input type="text" />');
	}
	inputPrompt.removeAttr("id");
	inputPrompt.removeAttr("name");
	inputPrompt.removeAttr("maxlength");
	inputPrompt.removeAttr("placeholder");
	inputPrompt.attr("class", target.attr("class"));
	inputPrompt.attr("data-focus", "filter");
	inputPrompt.attr("readonly", true);
	inputPrompt.css({"color":color});
	//过滤特殊类名
	if(options.filterClass){
		inputPrompt.removeClass(options.filterClass.replace(/,/g, " "));
	}
	target.get(0)._initTip = true;
	
	var init = function(){
		if($.trim(target.val())==""){
			target.val("");
			target.after(inputPrompt);
			target.hide();
			inputPrompt.val(target.attr("data-tip")); //每次赋值，避免页面赋值造成错误
			inputPrompt.bind({
				focus:function(){
					if(options.immediately || ""){
						inputPrompt.detach();
						target.show().focus();
					} else {
						setTimeout(function(){
							inputPrompt.detach();
							target.show().focus();
						});
					}
				}
			});
		}
	};
	target.bind({
		blur: function(){
			init();
		},
		focus:function(){
			$this = $(this);
			var text = $this.attr("placeholder") || $this.attr("data-tip");
			$this.removeAttr("placeholder");
			$this.attr("data-tip", text);
			inputPrompt.detach();
			$(this).show();
		},
		_reset:function(){
			if($.trim(target.val())==""){
				init();
			}
			else{
				target.show();
				if(inputPrompt){
					inputPrompt.hide();
					inputPrompt.remove();
				}
			}
		},
		removePlaceHolder:function(){
			$(this).show();
			inputPrompt.remove();
		}
	});
	init();
}

/**
 * 根据年月获取天数
 * @param Year
 * @param Month
 * @returns
 */
function dayNumOfMonth(Year,Month)
{
    var d = new Date(Year,Month,0);
    return d.getDate();
}

//以下三个方法配置page.jsp使用，进行相关换页工作
/**
 * 点击切换页面
 * 
 * @param el 下拉框元素
 */
function changePageByHref(el){
	el = $(el);
	var pageNo = el.val();
	location.href = baseUrl + "pageNo=" + pageNo;
}


/**
 * 删除url中参数
 */
function removeParam(url, params){
	var urlInfo = url.split("?");
	if(urlInfo.length == 2 && params &&  params.length > 0){
		var baseUrl = urlInfo[0];
		var urlParams = urlInfo[1];
		var paramInfo = urlParams.split("&");
		var newParams = [];
		for(var i=0; i<paramInfo.length; i++){
			var info =paramInfo[i].split("=");
			if($.inArray(info[0], params)==-1){
				newParams.push(paramInfo[i]);
			}
		}
		url = baseUrl+"?" + newParams.join("&");
	}
	return url;
}

//制保留1位小数，如：2，会在2后面补上0.即2.0  
function toDecimal(x) {  
    var f = parseFloat(x);  
    if (isNaN(f)) {  
        return false;  
    }  
    var f = Math.round(x*10)/10;  
    var s = f.toString();  
    var rs = s.indexOf('.');  
    if (rs < 0) {  
        rs = s.length;  
        s += '.';  
    }  
    while (s.length <= rs + 1) {  
        s += '0';  
    }  
    return s;  
}  

/**
 * 文件大小转换 保留小数点1 位
 */
function tranUnit(size){
	if (size == 0) {
		return "0 B";
	}
	var g_size = 1024 * 1024 * 1024;
	if (size >= g_size) {
		return toDecimal(size/g_size) + " GB";
	}
	var m_size = 1024 * 1024;
	if (size >= m_size) {
		return toDecimal(size/m_size) + " MB";
	}
	var k_size = 1024;
	if (size >= k_size) {
		return toDecimal(size/k_size) + " KB";
	}
	return toDecimal(size) +" B";
}

/**
 * ajax请求封装支持提示用户操作过期等常见错误
 */ 
function ajaxRequest(options){
	var settings = $.extend({
		errorMessage:"系统错误",
		errorRefresh:true,//系统错误是否刷新
		afterSuccess:function(data){},//返回成功后处理
		afterError:function(msg, data){}//返回错误处理
	}, options || {});
	
	var requestSettings = {
		type: "POST",
		async:true,
		dataType:"json",
		url : settings.url,
		data : settings.data||null,
		success:function(jsonResult, textStatus){
			var data = jsonResult.data ||{};
			if(jsonResult.type == "success"){
				settings.afterSuccess(data);
			}
			else{
				settings.afterError(jsonResult.msg, data);
			}
			
			if(data.refresh){
				reloadPage(1000);
			}
		},
		error:function(jqXHR, textStatus){
			if(textStatus=="error"){
				//这边延时处理,避免firefox浏览器页面跳转时，会触发ajax请求错误
				showMsg("登录超时，请重新登录", true, function(){
					location.href="site!logout.do";
				});
			}
			else{
				showError(settings.errorMessage);
				if(settings.errorRefresh){
					reloadPage(1000);
				}
			}
			
		}
	};
	$.extend(requestSettings, settings);
	return $.ajax(requestSettings);
}

/**
 * 中文算2个其他算一个
 * @param s
 * @returns {Number}
 */
function getLength(s) { 
	var l = 0; 
	var a = s.split(""); 
	for (var i=0;i<a.length;i++) { 
		if (a[i].charCodeAt(0)<299) { 
			l++; 
		} else { 
			l+=2; 
		} 
	} 
	return l; 
	}

/**
 * 获取事件当前位置
 * @param event
 * @returns
 */
function getEventPosition(event){
	if(event.pageX || event.pageY){
        return {x:event.pageX, y:event.pageY};
    }
    return {
        x:event.clientX + document.body.scrollLeft - document.body.clientLeft,
        y:event.clientY + document.body.scrollTop - document.body.clientTop
    };
}

function orderBy(key, type) {
	if (window.sortBaseUrl) {
		location.href = window.sortBaseUrl + "&orderKey=" + key + "&sortOrder="
				+ type;
	}
}

function reloadPage(timeout){
	timeout = timeout || 0;
	setTimeout(function(){
		if(window.sortBaseUrl){
			location.href = window.sortBaseUrl;
		} else {
			location.href = location.href;
		}
	}, timeout);
}

function getJsessionIdOfUrl(){
	var url = window.location.href;
	if(url.toLowerCase().indexOf("jsessionid") != -1) {
		if(url.indexOf("?") != -1) {
			return ";" + url.substring(url.toLowerCase().indexOf('jsessionid'),url.indexOf("?"));
		} else {
			return ";" + url.substring(url.toLowerCase().indexOf('jsessionid'),url.length);
		}
	}
	return "";
}

/**
 * 检测浏览器是否安装了flash 
 */
function flashChecker(){
		var swf = null;
		if(document.all){
			swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
		}
		else if(navigator.plugins && navigator.plugins.length > 0){
			swf = navigator.plugins["Shockwave Flash"];
		}

		if(swf){
			return true;	
		}
		return false;
}

/**
 * 浏览器辅助函数
 */
var BrowserHelper = {};
(function(){
	var ua = navigator.userAgent.toLowerCase();
	var check = function(r){
		return r.test(ua);
	};
	(function(browser){
		browser.isOpera = check(/opera/);
		browser.isIE = !browser.isOpera && check(/(msie\s|trident.*rv:)([\w.]+)/);
		browser.isIE6 = browser.isIE && check(/msie 6/);
		browser.isIE7 = browser.isIE && check(/msie 7/);
		browser.isIE8 = browser.isIE && check(/msie 8/);
		browser.isIE9 = browser.isIE && check(/msie 9/);
		browser.isIE11 = browser.isIE && check(/Trident/i);
		browser.isChrome = check(/chrome/);
		browser.isSafari = check(/safari/);
		browser.isUcbrowser = check(/ucbrowser/);
		browser.isIE7Mode = browser.isIE7 || (browser.isIE &&  document.documentMode && document.documentMode == 7);
	})(BrowserHelper);
})();

/**
 * 粘贴板
 * @param target
 * @param text
 * @returns {Boolean}
 * @author rubekid
 */
function clipboard(target, text, message){
	
	if(!flashChecker()){
		target.bind("click",function(){
			showError("您还未安装flash，复制功能无法使用");
		});
		return false;
	}
	target.each(function(){
		if(this._zclipInit){
			return false;
		}
		$(this).zclip({
			path : "/swf/ZeroClipboard.swf",
			copy : text || $(this).attr("data-text"),
			afterCopy : function(){
				showSuccess(message || "复制成功");
			}
		});
		this._zclipInit = true;
	});
	//IE6,IE7要对父级进行相对定位
	if(BrowserHelper.isIE6 || BrowserHelper.isIE7Mode){
		target.closest("div,li").css({
			position:"relative"
		});
	}
}



	

/**
 * 上传控件整理
 * @author rubekid
 * extendOptions //扩展自定义方法有
 * {
 *     invalidFileTypeError:"上传文件只支持{types}格式", //格式错误提示信息
 *     checkQueue:function(queueData){ //选择文件后队列校验, queueData.queueLength选择的文件队列长度
 *     		if(queueData.queueLength > 10){
 *     			showError("最多上传10张图片");
				return false;	
 *     		}
 *     		return true;
 *     },
 *     afterSuccess:function(result, target){//文件上传成功后回调 result：json格式返回信息，target当前控件对象
 *    		$("#thumbnail").attr("src", result.url);
 *     },
 *     afterComplete:function(uploadedCount, uploadedErrorCount){//全部上传完成后回调
 *          if(uploadedErrorCount==0){ //上传失败格式为0
 *     			showError("上传完成");
 *     		}
 *     }
 *     
 * }
 */
function fileUploadify(selector, extendOptions){
	extendOptions = extendOptions || {};
	var uploadifyEle = selector.get(0);
	var width = selector.outerWidth(false);
	var margin = selector.css("margin");
	if(margin==""){
		var ml = selector.css("marginLeft") || "0px";
		var mt = selector.css("marginTop") || "0px";
		var mr = selector.css("marginRight") || "0px";
		var mb = selector.css("marginBottom") || "0px";
		margin = mt + " " + mr + " " +mb + " " +ml;
	}
	var invalidFileTypeError = extendOptions.invalidFileTypeError||"上传文件只支持{types}格式";
	if(selector.is(":hidden")){//若按钮不可见时宽度获取会有问题
		var clone = selector.clone();
		clone.show();
		$(document.body).append(clone);
		width = clone.outerWidth(false);
		clone.remove();
	}
	var buttonText = selector.text();
	var containeSpace = /\s/.test(buttonText);
	if(containeSpace){
		width +=1;
	}
	
	var options = $.extend({
		fileObjName:"file",
		buttonText: selector.html(),
		swf  : ctxStatic+ '/uploadify/uploadify.swf',
		fileTypeDesc : '文件',
		fileTypeExts : '*.*',  
		width: width,
		removeTimeout:1,
		showProgress:true,
		overrideEvents  : ['onSelectError', 'onDialogClose'],
        onSelectError:function(file, errorCode, errorMsg){
        	var settings = this.settings;
            var message = extendOptions.message || {};
        	switch(errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    showError(message.QUEUE_LIMIT_EXCEEDED || "一次最多只能上传"+settings.queueSizeLimit+"个文件");
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                	showError(message.FILE_EXCEEDS_SIZE_LIMIT || "文件大小不能超过"+ settings.fileSizeLimit);
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                	if(file || ""){
                		showError(message.ZERO_BYTE_FILE || "文件 ["+file.name+"] 大小异常！");
                	} else {
                		showError(message.ZERO_BYTE_FILE || "文件上传失败，请重试！");
                	}
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                	var types = settings.fileTypeExts.replace(/\*/g, '').replace(/;/g, ' ');
                	var message = invalidFileTypeError.replace("{types}", types);
                	showError(message.INVALID_FILETYPE || message);
                    break;
            }
        },
        onDialogOpen : function(){
        	uploadifyEle.uploadedErrorCount = 0;
        	uploadifyEle.uploadedCount = 0;
        },
        onDialogClose : function(filesSelected, filesQueued, queueLength) {
        	$('#' + this.settings.queueID).hide();
        	if( this.queueData.queueLength==0 
        			|| this.queueData.filesErrored > 0
        			|| (typeof extendOptions.checkQueue == "function" && !extendOptions.checkQueue(this.queueData)) ){
        			
        		$('#' + this.settings.id).uploadify('cancel', "*");
				$('#' + this.settings.id).uploadify("stop");
        		return ;
        	}
        	$('#' + this.settings.id).uploadify('disable', true);
        	$('#' + this.settings.queueID).show().css({opacity:1});
		},
		onQueueComplete:function(file){
			$('#' + this.settings.id).uploadify('disable', false);
			$('#' + this.settings.queueID).fadeTo(1000, 0, function(){
				$(this).hide();
				if(typeof extendOptions.afterComplete == "function"){
					extendOptions.afterComplete(uploadifyEle.uploadedCount, uploadifyEle.uploadedErrorCount);
				}
			});
		},
		onUploadSuccess : function(file, result, response) {
			result = eval("("+result+")");
			var _this = this;
			var settings = this.settings;
        	uploadifyEle.uploadedCount++;
			if(result.error){
				uploadifyEle.uploadedErrorCount++;
				showError(result.message||"上传文件失败");
				if(result.errorType =="total_limit"){
					$('#' + settings.id).uploadify("stop");
		            $.each(this.queueData.files, function(){
		            	$("#" + this.id).hide();
		            	$('#' + settings.id).uploadify('cancel', this.id);
		            });
				}
			}
			else if(typeof extendOptions.afterSuccess == "function"){
				extendOptions.afterSuccess(result, this);
			}
		},
		onInit:function(target){
			var button = $('#' + target.settings.id);
			var buttonText =  button.find('.uploadify-button-text');	
			buttonText.addClass(selector.attr("class"));
			buttonText.css({"margin":"0px"});
			button.css({"margin": margin});

			if(extendOptions.button_disabled){
				$('#' + target.settings.id + '-button').addClass("disabled");
			}
			if(typeof extendOptions.afterInit == "function"){
				extendOptions.afterInit(target.settings);
			}
		}
	}, extendOptions);
	if(BrowserHelper.isIE6 || BrowserHelper.isIE7 || BrowserHelper.isIE8){
		selector.uploadify(options);
	}else{
		selector.H5ImageUploader(options);
	}
	
	selector.disable = function(){
		selector.uploadify('disable', true);//设置不可用
		selector.uploadify('settings', 'buttonCursor', 'arrow');
	};
	selector.enable = function(){
		selector.uploadify('disable', false);//设置可用
		selector.uploadify('settings', 'buttonCursor', 'hand');
	};
	selector.destroy = function(){
		selector.uploadify("destroy");
	};

	selector.setFormData = function(data){ //设置参数
		selector.uploadify("settings", "formData", data);
	};
	
	return selector;
}

/**
 * 图片上传
 * @see function fileUploadify
 */
function imageUploadify(selector, extendOptions){
	if(extendOptions || ""){
		if(extendOptions.uploader.indexOf("?") != -1){
			extendOptions.uploader += "&fileType=1";
		} else {
			extendOptions.uploader += "?fileType=1";
		}
	}
	var options = $.extend({
		fileObjName:"image",
		fileSizeLimit:"2MB",
		queueSizeLimit:1,
		multi:false,
		fileTypeDesc : '图片文件',
		fileTypeExts : '*.jpg;*.jpeg;*.gif;*.bmp;*.png',
		invalidFileTypeError:"上传图片只支持{types}格式"
	}, extendOptions||{});
	return fileUploadify(selector, options);
}

/**
 * 语音上传
 * @see function fileUploadify
 */
function audioUploadify(selector, extendOptions){
	if(extendOptions || ""){
		if(extendOptions.uploader.indexOf("?") != -1){
			extendOptions.uploader += "&fileType=2";
		} else {
			extendOptions.uploader += "?fileType=2";
		}
	}
	
	var options = $.extend({
		fileObjName:"audioFile",
		fileSizeLimit:"5MB",
		fileTypeDesc : '音频文件',
		fileTypeExts : '*.mp3;*.wma;*.wav;*.amr',
		queueSizeLimit:5,
		invalidFileTypeError:"上传语音只支持{types}格式"
	}, extendOptions||{});
	return fileUploadify(selector, options);
}

/**
 * 视频上传
 * @see function fileUploadify
 */
function videoUploadify(selector, extendOptions){
	if(extendOptions || ""){
		if(extendOptions.uploader.indexOf("?") != -1){
			extendOptions.uploader += "&fileType=3";
		} else {
			extendOptions.uploader += "?fileType=3";
		}
	}
	var options = $.extend({
		fileObjName : "videoFile",
		fileSizeLimit:"20MB",
		fileTypeDesc :'视频文件',
		fileTypeExts : '*.rm;*.rmvb;*.wmv;*.avi;*.mpg;*.mpeg;*.mp4',
		multi:false,
		queueSizeLimit:1,
		invalidFileTypeError:"上传视频只支持{types}格式"
	}, extendOptions||{});
	return fileUploadify(selector, options);
}


/**
 * 简单弹出框
 * @author rubekid
 */
(function($){
	
	var dialogTpl = '<div class="dialog" style="position:absolute;display:none;top:0;left:0;z-index:10999;">'
					 +'<form>'	
					  +'<div class="dialog_title">'
					    +'<div class="right_btn">'
					      +'<a href="javascript:;" class="btn_cancel"><img src="/images/admin/blank.gif"></a>'
					    +'</div>'
					    +'<span class="dialog_title_text"></span>'
					  +'</div>'
					  +'<div class="dialog_box">'
					    +'<div class="dialog_header" style="display:none;">'
					    +'</div>'
					    +'<div class="dialog_body">'					     
					    +'</div>'
					    +'<div class="c"></div>'
					    +'<div class="page_wrapper" style="height:29px;">'
					    +'</div>'
					    +'<div class="btn_box_zone">'
					      +'<a href="javascript:;" class="btn_confirm"><em>确 定</em></a>'
					      +'<a href="javascript:;" class="btn_cancel"><em>取 消</em></a>'
					    +'</div>'
					    +'<div class="c"></div>'
					  +'</div>'
					  +'</form>'
					+'</div>';	
	/**
	 * 弹出框 
	 */
	function Dialog(options){
		this.init(options);
	}
	
	Dialog.prototype = {
		init:function(options){
			this.options = options;
			this.container = $(dialogTpl);
			this.target = options.target;
			this.reposition = options.reposition;
			this.title = this.find(".dialog_title_text");
			this.dialogBox = this.find(".dialog_box");
			this.header = this.find(".dialog_header");
			this.body = this.find(".dialog_body");
			this.form = this.find("form");
			this.pageWrapper = this.find(".page_wrapper");
			this.btnBox = this.find(".btn_box_zone");

			var setting = $.extend({
				dialogClass:"dialog_w2",
				headerClass:"btn_box_x",
				dialogBoxClass:"prompt_box2",
				bodyClass:"appmsg_list",
				pageWrapperClass:"btn_box_x3 bor_t",
				btnBoxClass:"btn_box6",
				confirmBtnClass:"btn_auto2",
				cancelBtnClass:"btn_auto"
			}, options);

			this.container.addClass(setting.dialogClass);
			this.dialogBox.addClass(setting.dialogBoxClass);
			this.header.addClass(setting.headerClass);
			this.body.addClass(setting.bodyClass);
			this.pageWrapper.addClass(setting.pageWrapperClass);
			this.btnBox.addClass(setting.btnBoxClass);
			this.btnBox.find(".btn_confirm").addClass(setting.confirmBtnClass);
			this.btnBox.find(".btn_cancel").addClass(setting.cancelBtnClass);

			if(options.noHeader){
				this.header.remove();
			}
			if(options.noPage){
				this.pageWrapper.remove();
			}
			
			if(options.header){
				this.header.show().append(options.header);
			}
			if(options.headerStyle){
				this.header.css(options.headerStyle);
			}
			
			if(options.dialogTitleClass){
				this.find(".dialog_title").addClass(options.dialogTitleClass);
			}
			
			this.title.text(options.title||"");
			this.bodyHtml = options.body||"";
			$(document.body).append(this.container);

			this.createOverLayLayer();
			this.render();
		},
		find:function(selector){
			return $(selector, this.container);
		},
		/**
		 * 遮罩层 
		 */
		createOverLayLayer:function(){
			this._overLay = $('<div></div>');
			this._overLay.css({
				 top: 0,
				 bottom: 0,
				 left: 0,
				 right: 0,
				 position: "fixed",
				 background:"#000000",
				 opacity:0.5,
				 zIndex:9999
			});
			this._overLay.hide();
			$(document.body).append(this._overLay);
		},
		render:function(){
			var _this = this;
			if(this.target){
				this.target.bind("click", function(){
					_this.show();
				});
			}
			
			this.form.bind("submit", function(){
				return false;
			});
			
			this.find(".btn_cancel").bind("click", function(){
				_this.close();
			});
			
			
			this.find(".btn_confirm").bind("click", function(){
				if(typeof _this.options.confirm == "function"){
					if(_this.options.confirm(_this)){
						_this.close();
					}
				}
				else{
					_this.close();
				}
			});
			
			//设置输入框提示信息
			this.find('input[placeholder]').setPlaceHolder();
		},
		show:function(){
			var _this = this;
			var timeout = null;
			this.body.html(this.bodyHtml);
			this.body.find(":input").bindInputEvent();
			this.body.find(":input[maxlength]").maxLength();
			if(this.reposition){
				$(window).bind("scroll", function(){
					if(timeout){
						clearTimeout(timeout);
					}
					timeout = setTimeout(function(){
						if(_this.container.is(":visible")){
							_this.setPosition(true);
						}
					},30);
				});
			}
			

			this.container.show();
			this._overLay.show();
			if(typeof this.options.afterShow == "function"){
				this.options.afterShow(this);
			}
			this.setPosition();
			this.find("input.input_txt").focusHighlight();
		},
		close:function(){
			if(typeof this.options.onClose == "function"){
				this.options.onClose(this.body);
			}
			this.clear();
			this.container.hide();
			this._overLay.hide();
		},
		clear:function(){
			this.body.empty();
		},
		setPosition:function(animate){
			var width = this.container.outerWidth();
			var height = this.container.outerHeight();
			var top = $(document).scrollTop();
			var css = {
				marginTop: (top - height/2) +"px",
				marginLeft: -width/2 +"px",
				top : "50%",
				left : "50%"
			};
			if(animate){
				this.container.animate(css, 100);
			}else{
				this.container.css(css);
			}
			
		},
		getForm:function(){
			return this.form;
		},
		getBody:function(){
			return this.body;
		},
		getPageWrapper:function(){
			return this.pageWrapper;
		}
		
	};
	
	window.SimpleDialog = Dialog;
	
	$.fn.dialog = function(options){
		options = options ||{};
		
		return this.each(function(){
			var _options = $.extend({}, {
				target:$(this)
			}, options);
			this.dialog = new Dialog(_options);
		});
	};
	
	$.fn.shortDialog = function(options){
		options = options ||{};
		
		return this.each(function(){
			var _options = $.extend({}, {
				target:$(this),
				dialogBoxClass:"prompt_box",
				dialogClass:"dialog_w1",
				btnBoxClass:"btn_box",
				noPage:true
			}, options);
			this.dialog = new Dialog(_options);
		});
	};
	
})(window.jQuery);


/**
 * 分页列表
 * @author rubekid
 */

(function(){
	function PageList(options){
		this.init(options);
	}

	PageList.prototype = {
		init:function(options){
			var pageClass = options.pageClass || "page";
			this.renderHtml = options.renderHtml;
			this.beforePage = options.beforePage || function(){};//在翻页前触发
			this.afterPage = options.afterPage||function(){};//在翻页后促发
			this.baseUrl = options.baseUrl;
			this.form = options.form;
			this.wrapper = options.wrapper;
			this.pageWrapper = options.pageWrapper;
			this.body = options.body;
			this.autoInitData = options.autoInitData || false;
			this.useCache = options.useCache || false;
			this.cacheData = (options.cacheData||[]).slice(0);
			this.pageSize = options.pageSize || 10;
			this.defaultOrderKey = options.defaultOrderKey;
			this.defaultSortOrder = options.defaultSortOrder;
			this.pageNo = 1;
			this.pageElement = $('<div></div>');
			this.hasCheckAll = options.hasCheckAll || false;
			this.pageElement.addClass(pageClass);
			this.pageWrapper.append(this.pageElement);
			this.bindEvent();
			if(this.autoInitData){
				this.refreshPage(1);
			}
		},
		bindEvent:function(){
			if(!this.wrapper){
				return ;
			}
			var _this = this;
			var sortItems = this.wrapper.find(".sort_item");
			if(sortItems.length ==0){
				return ;
			}
			this.orderKey = this.form.find(":input[name='orderKey']");
			this.sortOrder = this.form.find(":input[name='sortOrder']");
			if(this.orderKey.length == 0){
				this.orderKey = $('<input type="hidden" name="orderKey" />');
				this.form.append(this.orderKey);
			}
			if(this.sortOrder.length == 0){
				this.sortOrder = $('<input type="hidden" name="sortOrder" />');
				this.form.append(this.sortOrder);
			}
			
			sortItems.attr("href","javascript:;").unbind("click");
			sortItems.bind("click", function(){
				var orderKey = $(this).data("key");
				var sortOrder = "asc";
				
				var sortClass = $(this).data("class");
				if(sortClass == "sort6"){
					sortOrder = "desc";
					sortClass = "sort5"
				}
				else{
					sortClass = "sort6";
				}
				
				_this.orderKey.val(orderKey);
				_this.sortOrder.val(sortOrder);
				_this.refreshPage(1);
				sortItems.find("img").attr("class", "sort7");
				sortItems.data("class", "sort7");
				$(this).find("img").attr("class", sortClass);
				$(this).data("class", sortClass);
			});
		},
		clearSort:function(){
			this.orderKey.val("");
			this.sortOrder.val("");
		},
		refreshPage:function(toPageNo, callback){
			toPageNo = toPageNo || this.pageNo;
			if(this.useCache){
				this.getPageListFromCache(toPageNo, callback);
			}
			else{
				this.getPageList(toPageNo, callback);
			}
		},
		createPage:function(totalCount, totalPages, pageNo){
    		var _this = this;
    		this.pageElement.prev().remove();
    		var checkAllDiv = '';
    		if(_this.hasCheckAll){
    			checkAllDiv = '<div style="float: left;"><input type="checkbox" class="input_align" id="checkAll" name="checkAll"/>全选</div>';
    		}
    		var pageHtml = "共"+totalCount+"条&nbsp;&nbsp;";
    		totalPages = totalPages == 0 ? 1 : totalPages;
    		if(totalPages!=1 && pageNo > 1){
    			pageHtml += '<a href="javascript:;" class="page_btn" data-type="page_no_first" >首页</a>';
    		}
    		else{
    			pageHtml += '<span class="color_03">首页</span>';
    		}
    		pageHtml +=' | ';
    		
    		if(totalPages > 1&& pageNo > 1 ){
    			pageHtml +='<a href="javascript:;" class="page_btn"  data-type="page_no_prev">上一页</a>';
    		}
    		else{
    			pageHtml +='<span class="color_03">上一页</span>';
    		}
    		pageHtml +=' | ';
    		
    		if(pageNo + 1 <= totalPages ){
    			pageHtml +='<a href="javascript:;" class="page_btn"  data-type="page_no_next">下一页</a>';
    		}
    		else{
    			pageHtml +='<span class="color_03">下一页</span>';
    		}
    		pageHtml +=' | ';
    		
    		if(totalPages > 1 && pageNo != totalPages){
    			pageHtml += '<a href="javascript:;" class="page_btn"  data-type="page_no_last" >末页</a>';
    		}
    		else{
    			pageHtml += '<span class="color_03">末页</span>';
    		}
    		pageHtml +='&nbsp;&nbsp;第'+pageNo+'页/共'+totalPages+'页&nbsp;&nbsp;';
    		pageHtml +='<select data-id="select_page">';
    		for(var i = 1; i <= totalPages; i++){
    			pageHtml +='<option value="'+i+'" '+ (i == pageNo ? 'selected="selected"' :'') +'>'+i+'</option>';
    		}
    		pageHtml +='</select>';
    		this.pageElement.html(pageHtml);
    		this.pageElement.before(checkAllDiv);
    		this.pageElement.find(".page_btn").bind("click", function(){
    			var toPageNo = 0;
    			switch($(this).data("type")){
    				case "page_no_first" : toPageNo = 1; break;
    				case "page_no_prev" : toPageNo = pageNo-1; break;
    				case "page_no_next" : toPageNo = pageNo+1; break;
    				case "page_no_last" : toPageNo = totalPages; break;
    				default:toPageNo=0;
    			}
    			if(toPageNo){
    				_this.refreshPage(toPageNo);
    			}
    		});
    		this.pageElement.find("[data-id='select_page']").bind("change", function(){
    			var toPageNo = $(this).val();
    			if(toPageNo){
    				_this.refreshPage(toPageNo);
    			}
    		});
    		
    		if(totalCount > 0){
    			this.pageWrapper.show();
    		}
    		else{
    			this.pageWrapper.hide();
    		}
    	},
    	getPageListFromCache:function(pageNo, callback){
    		var totalCount = this.cacheData.length;
    		var totalPages = Math.ceil(totalCount / this.pageSize);
    		if(pageNo == 0){
    			pageNo = 1;
    		}
    		if(pageNo > totalPages){
    			pageNo = totalPages;
    		}
    		var offset = this.pageSize * (pageNo -1);
    		var destData = this.sort(this.cacheData);
    		var data = {
   				totalCount:totalCount,
   				totalPages:totalPages,
   				pageNo:pageNo,
   				offset:offset,
   				list:destData.slice(offset, offset + this.pageSize)
    		};
			this.createPage(data.totalCount, data.totalPages, data.pageNo);
			var html = this.renderHtml(data||{});
			if(this.body && html){
				this.body.html(html);
			}
			this.pageNo = data.pageNo;
			this.afterPage(this.body);

			if(typeof callback == "function"){
				callback(data);
			}
    	},
    	getPageList:function(pageNo, callback){
    		var data = this.getFormData();
			pageNo = pageNo || 1;
			data.pageNo = pageNo;
			var _this = this;
			var wait = showWait();
			this.beforePage(this.body);
			$.ajax({
				type:"POST",
				url:this.baseUrl,
				data:data,
				dataType: "json",
				success:function(result){
					if(result.type =="success"){
						data = result.data;
						if(data){
							_this.createPage(data.totalCount, data.totalPages, data.pageNo);
							var html = _this.renderHtml(data||{});
							if(_this.body && html){
								_this.body.html(html);
							}
							_this.pageNo = data.pageNo;
							_this.afterPage(_this.body);
						}
						if(typeof callback == "function"){
							callback(data);
						}
					}
					else{
						if(result.errorType == "null" && result.msg == ""){
							showError("登录超时，请刷新浏览器或重新登录！");
						}else{
							showError(result.msg);
						}
					}
				},
				error:function(){
					showErrorMessage("登录超时，请刷新浏览器或重新登录！", "", function(){
						if(typeof doLogout == "function"){
						doLogout();
						}
					});
				},
				complete:function(){
					wait.hide();
				}
			});
    	},
    	getFormData:function(){
    		var arr = this.form.serializeArray();
    		var data = {};
    		for(var i =0 ; i< arr.length ; i++){
    			var item = arr[i];
    			data[item.name] = item.value;
    		}
    		return data;
    	},
    	setCacheData:function(cacheData){
    		cacheData = cacheData||[];
    		this.cacheData = cacheData.slice(0);
    		this.refreshPage(1);
    	},
    	find:function(selector){
    		return $(selector, this.body);
    	},
    	sort:function(srcData){
    		var formData = this.getFormData();
    		var _tmpData = srcData;
    		var orderKey = formData.orderKey || this.defaultOrderKey;
    		var sortOrder = formData.sortOrder || this.defaultSortOrder;
    		var flag = 1;
    		if(orderKey && _tmpData.length > 0){
    			if(sortOrder=="desc"){
    				flag = -1;
    			}
    			_tmpData.sort(function(a, b){
    				
    				var r = 0;
    				if(a[orderKey] > b[orderKey]){
    					r = 1;
    				}
    				else if(a[orderKey] < b[orderKey]){
    					r = -1;
    				}
    				return flag * r;
    			});
    		}
    		return _tmpData;
    	}
	};
	
	window.PageList = PageList;
})();



function openWindow(url ,width ,height){
	var width = width || 500;
	var height = height || 750;
	var left = (screen.width-width)/2;
	var top = (screen.height-height)/2;
	window.open("/site/sitePreview.do?url="+encodeURIComponent(url),'newwindow','height=' + height + ',width='+ width +',top='+ top +',left='+ left + ',toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no');
}

function showMsg(msg,isError,callBack){
	if(msg){
		if(isError){
			$('#noticeMessage').addClass('top_prompt_2');
		} else {
			$('#noticeMessage').removeClass('top_prompt_2');
		}
		$('#noticeMessage').html(msg);
		$('#noticeMessage').show();
		setTimeout( function(){
			$('#noticeMessage').html('');
			$('#noticeMessage').hide();
			if(callBack && typeof(callBack) == "function"){
				callBack();
			}
		} ,3000);
	}
}

function showSuccess(noticeMessage, gotoUrl) {
	$('#noticeMessage').removeClass('top_prompt_2');
	$('#noticeMessage').html(noticeMessage);
	$('#noticeMessage').animate({height:'show'});
	if(gotoUrl){
		setTimeout(function(){
			location.href=gotoUrl;
		},1000);
	}else{
		hideToast();
	}
}

function showUploadMessage(noticeMessage){
	$('#noticeMessage').removeClass('top_prompt_2');
	$('#noticeMessage').html(noticeMessage);
	$('#noticeMessage').animate({height:'show'});
	$("#upload_mask").show();
}

function showError(noticeMessage) {
	$('#noticeMessage').addClass('top_prompt_2');
	$('#noticeMessage').html(noticeMessage);
	$('#noticeMessage').animate({height:'show'});
	hideToast();
}

function hideUploadMessage(){
	$('#noticeMessage').html('');
	$('#noticeMessage').animate({height:'hide'});
	$("#upload_mask").hide();
}

function hideToast(timeout){
	timeout = timeout||3000;
	if(window._toast){
		clearTimeout(window._toast);
	}
	window._toast = setTimeout("$('#noticeMessage').html('');$('#noticeMessage').hide();", timeout);
}

/**
 * 类的继承
 * @param subClass
 * @param superClass
 * @param properties
 */
function inherits(subClass, superClass, properties){	
	properties = properties ||{};
    var F = function(){};
    F.prototype = superClass.prototype;
    //创建拷贝,不影响父类
	var nF=new F();
	//扩展子类方法		
	for(var key in properties){
		nF[key] = properties[key];
	}
	subClass.prototype=nF;
    subClass.prototype.constructor = subClass;
    subClass.superclass = superClass.prototype; //加了个属性指向父类本身以便调用父类函数
    if(superClass.prototype.constructor == Object.prototype.constructor){
        superClass.prototype.constructor = superClass;
    }
}

/**
 * 获取juicer模板
 * @param tplStr
 * @param data
 * @returns
 */
function fetchTpl(tplStr, data){
	if(!tplStr){
		return ""; 
	}
	data=data||{}; 
	return juicer(tplStr, data );
}

/**
 * 编译juicer
 * @param tpl
 * @returns
 */
function compiledTpl(tpl){
	if(!tpl){
		return ""; 
	}
	return juicer(tpl);
}



/**
 * 模拟下拉框 
 */
function selectRender(select){
	select.each(function(){
		$(this).selectRender();
		
		//显示提示信息时去掉默认选中第一个的样式
		if($(this).attr("editValue")){
			$(".selectbox-wrapper ul li:first", $(this).prev(".mainCon")).removeClass("selected");
		}
	});	
}


/**
 * 时间格式化
 * @author rubekid
 */
Date.prototype.format =function(format){
    var o = {
		"M+" : this.getMonth()+1, //month
		"d+" : this.getDate(),    //day
		"H+" : this.getHours(),   //hour
		"m+" : this.getMinutes(), //minute
		"s+" : this.getSeconds(), //second
		"q+" : Math.floor((this.getMonth()+3)/3),  //quarter
		"S" : this.getMilliseconds() //millisecond
    };
    var week = {         
	    "0" : "\u65e5",         
	    "1" : "\u4e00",         
	    "2" : "\u4e8c",         
	    "3" : "\u4e09",         
	    "4" : "\u56db",         
	    "5" : "\u4e94",         
	    "6" : "\u516d"
	};
	if(/(y+)/.test(format)) format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4- RegExp.$1.length));
	if(/(E+)/.test(format)) format=format.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[this.getDay()+""]);         
	for(var k in o)
		if(new RegExp("("+ k +")").test(format))
			format = format.replace(RegExp.$1,RegExp.$1.length==1? o[k] :("00"+ o[k]).substr((""+ o[k]).length));
	return format;
};



/***jquery 扩展****/
if (window.jQuery || window.Zepto) {
    (function ($) {
        'use strict';


		/**
		 * 判断是否支持oninput
		 */
		var input = document.createElement("input");
		var supportInput = "oninput" in input;


        /**
		 * tip 绑定提示信息 | 鼠标放上去显示提示信息
		 * @param options:{
		 * 		message : "<strong>商品浏览数：</strong><br />某时间段内……",// 可使用html标签,缺失将读取title
		 * 		timeout : 300, 	 //鼠标离开几毫秒后隐藏
		 *		position : "left", //默认居中，可配置值left 显示左下，right 显示右下
		 *		arrowLeft : 100, //选填 小箭头定位
		 *		offsetTop : -6,  //选填 垂直偏移量 
		 *		offsetLeft : 0   //选填 水平偏移量
		 * }
		 * @author rubekid
		 */
        $.fn.tip = function (options) {
        	options = options || {};
        	var timeout = options.timeout || 300; //鼠标离开几毫秒后隐藏
        	var arrowLeft = options.arrowLeft; //小箭头定位left
        	var offsetTop = options.offsetTop || 0; //垂直偏移量
        	var offsetLeft = options.offsetLeft ||0; //水平偏移量
        	
        	var prompt =  function(){
        		var html = '<ul class="order_pop_1" style="position:absolute;z-index:999;">'+
			                '<li>'+
			                  '<p class="prompt_note_content">'+
			                  '</p>'+
			                '</li>'+
			                '<i class="open_arrow" style="top:-12px;"></i>'+
			              '</ul>';
			              
			    var _prompt = $(html);
			    var _content = _prompt.find("p.prompt_note_content");
			    var _arrow =  _prompt.find("i.open_arrow");
			    _prompt.hide();
			    _prompt.appendTo(document.body);

			    if(options.style){
			    	_prompt.css(options.style);
			    }
			    
			    _prompt.bind({
			     	mouseover:function(){
			     		$(this).trigger("_show");
			     	},
			     	mouseout:function(){
			     		$(this).trigger("_hide");
			     	},
			     	_show:function(){
			     		if(this._timeout){
			     			clearTimeout(this._timeout);
			     			this._timeout = null;
			     		}
			     		$(this).stop();
			     		$(this).css({opacity:1});
			     		$(this).show();
			     	},
			     	_hide:function(){
			     		this._timeout = setTimeout(function(){
			    			_prompt.fadeOut(function(){
			    				_content.empty();
			    			});
			     		}, timeout);
			     	}
			    });
			    return {
			    	show:function(content, target){
			    		if(!arrowLeft){
			    			arrowLeft =  (_prompt.outerWidth(true) - _arrow.outerWidth()) / 2; 
			    		}

			    		var top = target.offset().top + target.outerHeight(true) + _arrow.height() + offsetTop;
			    		var style = {top:top};
			    		var position = options.position;
			    		var diff = (target.outerWidth() - _arrow.outerWidth()) / 2;
			    		
			    		if(position == "left"){//显示左下方
			    			style.left = target.offset().left + target.outerWidth(true) - _prompt.outerWidth(true) + offsetLeft;
			    			arrowLeft =  _prompt.outerWidth() - _arrow.outerWidth()  - target.css("marginRight").replace("px", "") - diff; 
			    		}
			    		else if(position == "right"){//显示右下方
			    			style.left = target.offset().left + offsetLeft;
			    			arrowLeft =  diff + target.css("marginLeft").replace("px", "");
			    			if(arrowLeft < 0){
			    				arrowLeft = 0;
			    			}
			    		}
			    		else{
			    			style.left = target.offset().left - arrowLeft + diff + offsetLeft;
			    		}
			    		
			    		_content.html(content);
			    		_prompt.trigger("_show");
			    		_prompt.css(style);
			    		_arrow.css({
			    			left:arrowLeft+"px"
			    		});
			    	},
			    	hide:function(){
			    		_prompt.trigger("_hide");
			    	}
			    };
        	}();
        	
            return this.each(function(){
            	this._message  = options.message || this.title || $(this).data("tip") || $(this).data("note") || this._message;
            	this.title = "";
            	$(this).unbind("mouseover").unbind("mouseout");
	    		$(this).bind({
	    			mouseover:function(){
	    				var note = this._message;
	        			if(note){
	        				prompt.show(note, $(this));
	        			}
	    			},
	    			mouseout:function(){
	    				prompt.hide();
	    			}
	    		});
            });
        };
        
        /**
         * 显示二维码
         * @author rubekid
         */
        $.fn.showQrcode = function(src){
        	return this.each(function(){
        		src = $(this).attr("data-qrcode") || src;
        		$(this).tip({
        			top:-4,
        			message:'<img width=100 height=100 src="'+src+'">',
        			style:{
	        			width:$(this).outerWidth() - 40 +"px", // padding:5px 20px;
	        			"text-align":"center"
        			}
        		});
        	});
        };
        
        /**
         * 弹出排序
         */
        $.fn.invokeSort = function(options){
        	var url = options.url;
        	var sortName = options.sortName || "displayOrder"; //提交到后台排序属性名称
			var body = '<p>请输入您想要排序数字，范围1-1000：</p><input class="input_txt input_txt_on input_txt_w1" data-type="number" maxlength="4" maxnumber="1000" zero="false" type="text" name="displayorder" />';
			var refresh = function(){
				setTimeout(function(){
					reloadPage();
				}, 1000);
			};
        	return this.each(function(){
        		var index = $(this).data("index");
        		var id = $(this).data("id");
        		var data = {id:id};
        		
        		var dialog = new SimpleDialog($.extend({
    				target:$(this),
    				title:"排序",
    				dialogBoxClass:"prompt_box",
    				dialogClass:"dialog_w1",
    				btnBoxClass:"btn_box",
    				noPage:true,
    				body:body,
    				afterShow:function(target){
    					target.getBody().html(body);
    					var input = target.find(":input[name='displayorder']");
    					input.numberFormat();
    					input.val(index);
    					input.focus();
    				},
    				confirm:function(target){
    					var input = target.find(":input[name='displayorder']");
    					var sortValue=$.trim(input.val());
    					if(sortValue == ""||isNaN(sortValue)||parseInt(sortValue)<=0){
    						showError("请输入您想要排序数字，范围1-1000");
    						return false;
    					}
    					data[sortName] = sortValue;
    					var rsyncWaitEl = showWait();
    					$.ajax({
    						type : "POST",
    						url : url,
    						data:data,
    						dataType : "json",
    						success : function(result) {
    							if (result.type == "success") {
    								showSuccess("排序成功");
    								refresh();
    							} else {
    								showError(result.msg||"排序失败");
    								if(result.refresh){
    									refresh();
    								}
    							}
    							target.close();
    						},
    						error:function(){
    							showError("排序失败");
    							refresh();
    						},
    						complete:function(){
    							rsyncWaitEl.hide();
    						}
    					});
    					return false;
    				}
    			}, options.dialogConfig||{}));
        	});
        };
        
        /**
         * 切换状态
         */
        $.fn.switchState = function(options){
        	var url = options.url;
        	var stateName = options.stateName || "state";
        	var enableText = options.enableText || "开启";
        	var disableText = options.disableText || "关闭";
        	var enableClass = options.enableClass || "color_01";
        	var disableClass = options.disableClass || "color_02";
        	
        	return this.bind("click", function(){
        		var state = 1;
        		var id = $(this).attr("data-id");
        		if($(this).attr("data-state") == 1){
        			state = 0;
        		}
        		var data = {id:id};
        		data[stateName] = state;
        		var rsyncWaitEl = showWait();
        		var _this = this;
        		$.ajax({
        			type : "POST",
        			url : url,
        			data : data,
        			dataType : "json",
        			success : function(result) {
        				if (result.type == "success") {
        					if(state == 1){
        						$(_this).html('<span class="'+enableClass+'">'+enableText+'</span>');
        					}
        					else{
        						$(_this).html('<span class="'+disableClass+'">'+disableText+'</span>');
        					}
        					$(_this).attr("data-state", state);
        				}
        				else{
        					showError(result.msg||"操作失败");
        				}
        			},
        			error:function(){
        				showError("操作失败");
        			},
        			complete:function(){
        				rsyncWaitEl.hide();
        			}
        		});
        		
        	});
        };
        
        /**
         * 恢复默认值
         * @author rubekid
         */
        $.fn.recovery = function(){
        	return this.each(function(){
        		var defaultValue = $(this).attr("data-default")||"";
        		if(defaultValue!=""){
        			$(this).unbind("blur");
	        		$(this).bind({
	        			blur:function(){
	            			if($.trim($(this).val()) == ""){
	            				$(this).val(defaultValue);
	            			}
	            		}
	        		});
        		}
        		if($.trim($(this).val()) == ""){
        			$(this).val(defaultValue);
        		}
        	});
        };
        
        /**
         * 设置输入灰色提示值
         * @author rubekid
         */
        $.fn.setPlaceHolder = function(options){
        	return this.each(function(){
        		var _options = $.extend({}, options||{});
        		setPlaceHolder($(this), _options);
        	});
        };
        
        /**
         * 绑定input事件
         */
        $.fn.bindInput = function(func){
        	return this.bind({
        		keyup:func,
        		paste:function(){
        			var _this = this;
        			setTimeout(function(){
        				$(_this).trigger("_inputEvent");
        			},10);
        		},
        		_inputEvent:func
        	})
        };

		$.fn.bindInputEvent = function(){
			var keyEvent = supportInput ? "input":"keyup";
			this.bind("paste", function(e){
				var _this = this;
				setTimeout(function(){
					$(_this).trigger("_input");
				},10);
			});
			if(!supportInput){
				this.bind("keydown", function(e){
					var _this = this;
					setTimeout(function(){
						$(_this).trigger("_input");
					},0);
				});
			}
			this.bind(keyEvent, function(e){
				$(this).trigger("_input");
				
			});
			return this;
		};

		$.fn.numberFormat = function(){
			this.bindInputEvent();
			return this.bind({
				_input:function(){
					var number = $.trim($(this).val());
					if($(this).attr("zero")=="false"||number != '0'){
						number = number.replace(/[^\d]/g, "").replace(/^0+/g, '');
					}
					if($(this).attr("maxnumber")){
						var maxnumber = parseInt($(this).attr("maxnumber"));
						while(number > maxnumber){
							number = Math.floor( number / 10 );
						}
					}
					
					if(number != $(this).val() || number==''){
						$(this).val(number);
					}

				}
			});
		};

		$.fn.moneyFormat = function(){
			this.bindInputEvent();
			return this.bind({
				_input:function(){
					var number = $.trim($(this).val());
					var tmp = number;
					if(number != '0' && number !=''){
						number = number.replace(/[^\d\.]/g, "").replace(/^\./g,'');
						var arr = number.split('.', 2);
						if(arr[0]!=''){
							if(parseInt(arr[0]) == 0)
								arr[0] = 0;
							else
								arr[0] = arr[0].replace(/\b(0+)/gi,"");
						}
						if(arr.length == 2){
							var decimalDigit = $(this).attr("decimal-limit");
							if(decimalDigit == null || decimalDigit.length == 0)
								arr[1] = arr[1].substr(0, 2);
							else{
								arr[1] = arr[1].substr(0, decimalDigit);
							}
						}
						number = arr.join('.');
					}
					if($(this).attr("maxnumber")){
						var maxnumber = $(this).attr("maxnumber") * 1;
						while(number > maxnumber){
							number = Math.floor( number / 10 );
						}
					}

					if(number != tmp || number==''){
						$(this).val(number);
					}
				}
			});
		};
		
		/**
		 * 百分数格式化
		 */
		$.fn.percentFormat = function(){
			this.bindInputEvent();
			return this.bind({
				_input:function(){
					var number = $.trim($(this).val());
					var tmp = number;
					var maxnumber = 100;
					if(number != '0' && number !=''){
						number = number.replace(/[^\d\.]/g, "").replace(/^\./g,'');
						var arr = number.split('.', 2);
						if(arr[0]!=''){
							if(parseInt(arr[0]) == 0)
								arr[0] = 0;
							else
								arr[0] = arr[0].replace(/\b(0+)/gi,"");
						}
						if(arr.length == 2){
							var decimalDigit = $(this).attr("decimal-limit");
							if(decimalDigit == null || decimalDigit.length == 0)
								arr[1] = arr[1].substr(0, 2);
							else{
								arr[1] = arr[1].substr(0, decimalDigit);
							}
						}
						number = arr.join('.');
					}
					if($(this).attr("maxnumber")){
						var _maxnumber = $(this).attr("maxnumber") * 1;
						if(_maxnumber < maxnumber){
							maxnumber = _maxnumber;
						}
					}
					
					while(number > maxnumber){
						number = Math.floor( number / 10 );
					}

					if(number != tmp || number==''){
						$(this).val(number);
					}
				}
			});
		};
		
		$.fn.integerFormat = function(){
			this.bindInputEvent();
			return this.bind({
				_input:function(){
	    			var number = $.trim($(this).val());
	    			var t = number.charAt(0); 
	    			var tmp = number;
	    			if($(this).attr("zero")=="false"||number != '0'){
	    				number = number.replace(/[^\d]/g, "").replace(/^0/g, '');
	    			}
	    			if($(this).attr("maxnumber")){
	    				var maxnumber = parseInt($(this).attr("maxnumber"));
	    				while(number > maxnumber){
	    					number = Math.floor( number / 10 );
	    				}
	    			}
	    			//如果第一位是负号，则允许添加   如果不允许添加负号 可以把这块注释掉
	    			if (t == '-') {
	    				number = '-' + number;
	    	        }
	    			if(number != tmp){
	    				$(this).val(number);
	    			}
	    		}
			});
		};
		
		$.fn.negativeMoneyFormat = function(){
			this.bindInputEvent();
			return this.bind({
				_input:function(){
	    			var number = $.trim($(this).val());
					var tmp = number;
					if(number != '0' && number !=''){
						var inputValue = number.charAt(0);
						number = number.replace(/[^\d\.]/g, "").replace(/^\./g,'');
						if(inputValue == "-"){
							number = "-" + number;
						}
						var arr = number.split('.', 2);
						if(arr[0]!=''){
							if(parseInt(arr[0]) == 0) {
								arr[0] = 0;
							} else {
								arr[0] = arr[0].replace(/\b(0+)/gi,"");
							}
						}
						if(arr.length == 2){
							var decimalDigit = $(this).attr("decimal-limit");
							if(decimalDigit == null || decimalDigit.length == 0)
								arr[1] = arr[1].substr(0, 2);
							else{
								arr[1] = arr[1].substr(0, decimalDigit);
							}
						}
						number = arr.join('.');
					}
					if($(this).attr("maxnumber")){
						var maxnumber = $(this).attr("maxnumber") * 1;
						while(number > maxnumber){
							number = Math.floor( number / 10 );
						}
					}

					if(number != tmp || number==''){
						$(this).val(number);
					}
	    		}
			});
		};
		
		$.fn.focusHighlight = function(){
			return this.bind({
	    		focus : function(){
	    			$(this).addClass('input_txt_on');
	    		},
	    		blur : function(){
	    			$(this).removeClass('input_txt_on');
	    		}
	    	});
		};
		
		$.fn.maxLength = function(){
			return this.bind({
	    		_input:function(){
	    			if($(this).attr("maxlength") > 0 && $(this).val().length > $(this).attr("maxlength")){
	    				$(this).val($(this).val().substr(0,  $(this).attr("maxlength")));
	    			}
	    		}
	    	});
		};

        
    })(window.jQuery || window.Zepto);
    
    
   
    $(function(){
    	
    	/**
    	 * 初始化拦截器 
    	 */
    	if(typeof window.initInputEventInterceptor == "function"){
    		var result = window.initInputEventInterceptor();
    		if(typeof result != "undefined" && result === false ){
    			return false;
    		}
    	}
    	
    	$("textarea[maxlength],input[data-type='number'],input[data-type='money'],input[data-type='limit'],input[data-type='negativeNumber'],input[data-type='negativeMoney']").bindInputEvent();
    	
    	/**
         * 可恢复输入框 为空失去焦点恢复默认值
         */
    	$("input[data-default]").recovery();
    	
    	/**
    	 * 设置输入框的提示值
    	 */
    	$("input[placeholder]").setPlaceHolder({filterClass:"input_txt_on"});
    	
    	
    	/**
         * 对textarea maxlength的兼容
         */
    	$("textarea[maxlength]").maxLength();
    	
    	/**
         * 限制input只能输入数值
         */
    	$("input[data-type='number']").numberFormat();

    	/**
         * 限制input只能输入正负整数值
         */
    	$("input[data-type='negativeNumber']").integerFormat();
    	
    	/**
    	 * 限制input只能输入正负金额
    	 */
    	$("input[data-type='negativeMoney']").negativeMoneyFormat();
    	
    	/**
         * 限制input只能输入金额
         */
    	$("input[data-type='money']").moneyFormat();
    	
    	/**
         * 限制input只能百分比
         */
    	$("input[data-type='percent']").percentFormat();
    	
    	/**
         * 限制input只能输入大于0的整数 默认值为-1 表示无限
         */
    	$("input[data-type='limit']").each(function(){
    		var defaultValue = $(this).attr("data-default") || "-1";
    		$(this).attr("data-default", defaultValue);
    		$(this).bind({
    			_input:function(){
	    			var number = $.trim($(this).val());
	    			var tmp = number;
	    			if(defaultValue.indexOf(number) == -1){
	    				if(number.indexOf(defaultValue) == 0){
	    					number = defaultValue;
	    				}
	    				else{
	    					if($(this).attr("zero")=="true"&&number == '0'){
	    	    				number = number.replace(/[^\d]/g, "");
	    	    			}else{
	    	    				number = number.replace(/[^\d]/g, "").replace(/^0/g, '');
	    	    			}
	    				}
	    			}
	    			if(number != tmp){
	    				$(this).val(number);
	    			}
	    		}
    		});
    		$(this).recovery();
    	});
    	
    	/**
    	 * 输入框聚焦与失焦样式
    	 */
    	$("input.input_txt:not([data-focus='filter'])").focusHighlight();
    	$("textarea[class^='textarea']:not([data-focus='filter'])").focusHighlight();
    });
}

/**
 * 是否微信访问
 * 
 * @returns {Boolean}
 */
function isWxUserAgent() {
	if (navigator.userAgent.indexOf('MicroMessenger') > 0) {
		return true;
	}
	return false; 
}


function initListSubmitForm(){
	if ($("form").find("input[type='submit']").length <= 0) {
		$("form input").keypress(function(event){
			if(event.keyCode == 13){
				$("form").submit();
			}
		});
	}
}

function getDateByDuration(duration, format){
	var today = new Date();
	var from = new Date();
	var to = new Date();
	var format = format || "yyyy-MM-dd";
	var dayMillisec = 24 * 60 * 60 * 1000;
	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);
	
	to.setTime(today.getTime() - dayMillisec);//最近几天从昨天开始算
	from.setTime(to.getTime() - (duration - 1) * dayMillisec);
	return {
		from:from.format(format),
		to:to.format(format)
	};
}

function drawHighcharts(config){
	config = config || {};
	var categories = config.categories||[];
	var series = config.series||[];
	var step = Math.ceil((categories.length||0) / 10);
	var labels = { step : step, maxStaggerLines : 1};
	var formatter = config.formatter || function(){
        return this.x + '<br />' + name + "  " + this.y;
    };
	return new Highcharts.Chart($.extend(true, {
		title: {
	        text: ''
	    },
	    chart: {
	        renderTo: 'chartContain',
	        type: 'line',
	        marginTop:20
	    },
	    xAxis: {
	        categories: categories,
	        labels:labels
	    },
	    yAxis: {
	        title:{
	            text: ''
	        }
	    },
	    tooltip: {
	        formatter: formatter
	    },
	    legend: {
	        verticalAlign: 'bottom',
	        x: 0,
	        borderWidth: 0,
	        enabled:true
	    },
	    series: series
	}, config.extendOptions));
}

/**
 *封装ajax提交数据
 */
jQuery.ajaxEditData = function(config) {
	$.ajax({
		type : config.type,
		url :  config.url,
		data : config.data,
		dataType : config.dataType,
		cache: config.cache,
		beforeSend: function(){
			if(config.beforeSend){
					config.beforeSend();
			}
		},
		success : function(result){
			config.success(result);
		},
		error:function(){
			showErrorMessage("登录超时，请刷新浏览器或重新登录！", "", function(){
				if(typeof doLogout == "function"){
				doLogout();
				}
			});
		},
		complete:function(){
			if(config.complete){
				config.complete();
			}
		},
		async:config.async
		});
};

/**
 * 多行缩略
 * @author rubekid
 * {
 *    maxLine:2, //最多显示行默认为1
 *    ellipsisChar:"..." //省略占位符，建议不设置，与原生一致 
 * }
 */
(function ($) {
	
	var supportLineClamp = function(){
		var div = document.createElement('div');
		var style = computeStyle(div);
		return style!=null && "-webkit-line-clamp" in style;
	}();
	

	function computeStyle(el){
		if(window.getComputedStyle){
		
			return window.getComputedStyle(el,null); 
		}
		return el.currentStyle;
	}

	/**
	 * 设置样式
	 * @param Element el
	 * @param JSON css
	 */
	function setStyle(el, css){
		for(var i in css){
			el.style[i] = css[i];
		}
	}

    function ellipsis($elem, options) {
    	var maxLine = options.maxLine ||1;
    	var lineHeight = parseFloat($elem.css("line-height"));
        var maxHeight = maxLine * lineHeight;
        var content = $elem.attr("data-content") || $elem.text();
        var $temp_elem = $elem.clone(false)
            .css({"visibility": "hidden","overflow":"visible", "height":"auto"})
            .appendTo($elem.parent());
        $temp_elem.text(content);
        var height = $temp_elem.height();
		if(height > maxHeight){
			if(supportLineClamp){
				setStyle($elem.get(0), {
					"text-overflow":"ellipsis",
				    "display":"-webkit-box",
				    "-webkit-line-clamp":maxLine,
				    "-webkit-box-orient":"vertical",
				    "overflow":"hidden"
				});

			}
			else{
			
				var _width = $elem.width();
				var ellipsis_char = options.ellipsisChar;
				var lineCount = 0;
		        var texts = content.split("\n", maxLine);
		        var newTexts = [];
		        for(var i=0; i<texts.length; i++){
		        	var text = texts[i];
		        	$temp_elem.text(text);
		        	height = $temp_elem.height();
		        	var _lineCount = height / lineHeight;
		        	if(lineCount + _lineCount >= maxLine){
		        		text = text + ellipsis_char;
		        		$temp_elem.text(text);
		        		text = text.replace(' ','　'); //for fix white-space bug　
		        		$temp_elem.css({"whiteSpace": "nowrap","width":"auto" });
		        		var max = (maxLine - lineCount) * _width;
			        	var width = $temp_elem.get(0).scrollWidth;
			        	if(width > max){
			    			var stop =  Math.floor(text.length * max / width); // for performance while content exceeding the limit substantially
			    			var temp_str = text.substring(0,stop) + ellipsis_char;
			    			width = $temp_elem.text(temp_str).get(0).scrollWidth;
			    			if(width > max){
			    				while (width > max && stop > 1) {
			    					stop--;
			    					temp_str = text.substring(0, stop) + ellipsis_char;
			    					width = $temp_elem.text(temp_str).width();
			    				}					
			    			}
			    			else if(width < max){
			    				while (width < max && stop < text.length) {
			    					stop++;
			    					temp_str = text.substring(0, stop) + ellipsis_char;
			    					width = $temp_elem.text(temp_str).get(0).scrollWidth;
			    				}
			    				if(width > max){
			    					temp_str = text.substring(0,stop -1)+ellipsis_char;
			    				}
			    			}
			    			
			    			newTexts.push(temp_str.replace('　',' '));
			    		}
			        	else{
			        		newTexts.push(text);
			        	}
			        	break;
		        	}
		        	newTexts.push(text);
		        	lineCount +=_lineCount;
		        	
		        }
		        text = newTexts.join("\n");
		        $temp_elem.text(text).css(
		        	{"whiteSpace": "","width": $elem.width() }
		        );
		        var lastIndex = text.length;
		        var _temp_str = text;
		        height = $temp_elem.height();
	        	while(height > maxHeight){
	        		_temp_str = text.substring(0, --lastIndex) + ellipsis_char;
	        		$temp_elem.text(_temp_str);
	        		height = $temp_elem.height();
	        	}
		        
		        $elem.text(_temp_str);
			}
		}
		$temp_elem.remove();
    }


    var defaults = {
        maxLine: 1,
		ellipsisChar:'...'
    };

    $.fn.ellipsis = function (options) {
        return this.each(function () {
            var $elem = $(this);
            var opts = $.extend({}, defaults, options);
            ellipsis($elem, opts);
        });
    };

    $.fn.ellipsis.options = defaults;
})(jQuery);

var EmoticonUtils = {
		init:function(options){
			this._data = options.data;
			this._dynamicPath = options.dynamicPath;
		},
		toEmoticon:function(e, width) {
			width = width || 28;
			var _this = this;
			var t, n,
			o = this._data;
			var replace = '<img src="{src}" alt="mo-{alt}" width="'+width+'" />';
			for (t in o) {
				n = new RegExp("/" + o[t], "g"),
				e = e.replace(n, replace.format({
					src: _this._dynamicPath + t + '.gif',
					alt: o[t]
				}));
			}
			return e;
		}
};

/**
 * 字符串格式化
 * @author rubekid
 */
String.prototype.format = function(args) {
	var result = this;
	if (arguments.length > 0) {    
		if (arguments.length == 1 && typeof (args) == "object") {
        	for (var key in args) {
                if(args[key]!=undefined){
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                	var key = "({)" + i + "(})";
                	var reg= new RegExp(key, "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
};

/**
 * 初始化编辑器统一方法,需配合编辑器相关JS使用
 */
function initSimpleEditor(elementName,options){
	var toolbars = [[ 'fullscreen','bold', 'italic', 'underline', 'forecolor', 'backcolor','fontsize',
						'|','justifyleft', 'justifycenter', 'justifyright','lineheight', 
						'|','insertimage','selectlib', 'link', 'unlink','inserttable' | 'editmore']];
	var config = $.extend({
			  toolbars:toolbars,
			  autoFloatEnabled:false
	},options || {});
	
	 var contentEditor = new baidu.editor.ui.Editor(config);
	 contentEditor.render(elementName);
	 return contentEditor;
}


/**
 * 二维码鼠标显示事件
 */
function qcodeShow(){
	var $qrcode = $("i[class='scene_code']");
	$qrcode.bind({
		mouseover:function(){
			$(".scene_pop_1").hide();
			$(".scene_arrow_r").hide();
			var aEle = $(this).parent();
			aEle.prev().show();
			aEle.next().show();
		},
		mouseout:function(){
			var aEle = $(this).parent();
			var prev = aEle.prev();
			var arrow = aEle.next();
			prev.get(0)._handler = setTimeout(function(){
				prev.hide();
				arrow.hide();
			}, 300);
		}
	});
}

/**
 * 初始化编辑器
 * @param target
 * @param config
 */
function initEditor(element, config){
	$(element).each(function(){
		var  target = $(this);
		target.summernote({
			lang: 'zh-CN',
			height: "500px",
			callbacks: {
				onImageUpload: function(files) {
					var formData = new FormData();
					for(var i=0; i<files.length; i++){
						formData.append('images',  files[i]);
					}
					Modal.loading("图片上传中");
					
					$.ajax({
						url : window.ctx + "/sys/uploader/images",
						type : 'POST',
						data : formData,
						processData : false,
						contentType : false,
						success : function(response) {
							if(response && response.length > 0){
								for(var i=0; i<response.length ; i++){
									target.summernote('insertImage', response[i].url,'img');
								}
							}
						},
						complete:function(){
							Modal.dismissLoading();
						}
					});
				}
			}
		});
	});

}